package com.itheima.ssm.dao;


import com.itheima.ssm.domain.Permission;
import com.itheima.ssm.domain.Role;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Service;

import java.util.List;

public interface IRoleDao {

//  根据用户id查询出所有对应的角色

    @Select("SELECT *  FROM role WHERE id in (SELECT roleId from users_role WHERE userId =#{userId})")
    @Results({
            @Result(id = true, property = "id", column = "id"),
            @Result(property = "roleName", column = "roleName"),
            @Result(property = "roleDesc", column = "roleDesc"),
            @Result(property = "permissions", column = "id", javaType = java.util.List.class,
                    many = @Many(select = "com.itheima.ssm.dao.IPermissionDao.findPermissionByRoleId")),
    })
    List<Role> findRoleByUserId(String userid) throws Exception;

    //查询所有的角色
    @Select("select * from role")
    List<Role> findAll() throws Exception;

    @Insert("insert into role(roleName,roleDesc) values (#{roleName},#{roleDesc})")
    void save(Role role) throws Exception;

    //    角色详情
    @Select("select * from role where id=#{roleId}")
    @Results({
            @Result(id = true, property = "id", column = "id"),
            @Result(property = "roleName", column = "roleName"),
            @Result(property = "roleDesc", column = "roleDesc"),
            @Result(property = "permissions", column = "id", javaType = java.util.List.class,
                    many = @Many(select = "com.itheima.ssm.dao.IPermissionDao.findPermissionByRoleId"))
    })
    Role findById(String roleId) throws Exception;

    //删除角色[role包含两个中间表]
    @Delete("delete from users_role where roleId=#{roleId}")
    void delFromUser_roleByRoleId(String roleId) throws Exception;

    @Delete("delete from role_permission where roleId =#{roleId}")
    void delFromUser_permissinonByRoleId(String roleId) throws Exception;

    @Delete("delete from role where id =#{roleId}")
    void delFromRoleByRoleId(String roleId) throws Exception;

    /*根据roleId查询出该角色没有的所有权限*/
    @Select("select * from permission where id not in (select permissionId from role_permission where roleId =#{roleId})")
    List<Permission> findRoleByIdAndAllPermission(String roleId) throws Exception;

    /*根据roleId查询出该角色没有的所有权限 添加中间表*/
    @Insert("insert into role_permission (permissionId,roleId) values (#{permissionId},#{roleId})")
    void addPermissionToRole(@Param("roleId") String roleId, @Param("permissionId") String permission) throws Exception;
}
